import React, { Component } from 'react'
import { Input, message, Spin, Table } from "antd"
import { RootState } from '../../reducers'
import { connect, ConnectedProps } from 'react-redux'
import ArticleInfo from "../../types/ArticleInfo";
import {
    listArticleInfoReq,
    listArticleOnID,
    queryArticleAmount,
    queryArticleAmountOnID,
    searchArticleInfo,
    searchArticleInfoOnID
} from "../../requests/article";
import moment from 'moment';
import { getRes } from "../../configFile";
import ArticleType from "../../types/ArticleType";
import UserType from "../../types/UserType";

const { Search } = Input;

interface PropsFromRedux extends ConnectedProps<typeof connector> {
    articleType: ArticleType
}

interface IState {
    ArticleSource: Array<Pick<ArticleInfo, "articleID" | "articleType" | "title" | "authorID" | "creationTimestamp" | "lastModifiedTimestamp">
        &
    { key: number }
    >
    amount: number
    offset: number
    limit: number
    isSearch: boolean
    isLoading: boolean
}

export class ArticleInfoList extends Component<PropsFromRedux, IState> {
    constructor(props: PropsFromRedux) {
        super(props)
        this.state = {
            isLoading: true,
            ArticleSource: [],
            amount: 0,
            offset: 0,
            limit: 10,
            isSearch: false
        }
    }

    //获取设备知识数据
    getArticle = async () => {
        try {
            const amountRes = this.props.userType === UserType.SUPERVISOR ?
                getRes(await queryArticleAmount(this.props.articleType))
                :
                getRes(await queryArticleAmountOnID(this.props.articleType, this.props.userID))
            const res = this.props.userType === UserType.SUPERVISOR ?
                getRes(await listArticleInfoReq(this.props.articleType, this.state.offset, this.state.limit))
                :
                getRes(await listArticleOnID(this.props.articleType, this.state.offset, this.state.limit, this.props.userID))
            if (amountRes.isSuccessful && res.isSuccessful) {
                this.setState({
                    ArticleSource: res.data.map((item: ArticleInfo) => Object.assign({}, item, { key: item.articleID })),
                    amount: amountRes.data
                })
            } else {
                console.error(amountRes);
                console.error(res);
                message.error("获取设备知识失败")
            }
        } catch (error) {
            message.error(error.toString())
        }
    }

    async componentDidMount() {
        this.setState({ isLoading: true })
        await this.getArticle()
        this.setState({ isLoading: false })
    }

    onSearch: (values: string) => void = async values => {
        if (values === '') {
            await this.getArticle();
        } else {
            try {
                const res = this.props.userType === UserType.SUPERVISOR ?
                    getRes(await searchArticleInfo(values, this.props.articleType))
                    :
                    getRes(await searchArticleInfoOnID(this.props.articleType, values))
                if (res.isSuccessful) {
                    this.setState({ ArticleSource: res.data, amount: res.data.length, isSearch: true })
                } else {
                    message.error("查询失败")
                }
            } catch (err) {
                message.error(JSON.stringify(err))
            }
        }
    }

    columns = [{
        title: '文章标题',
        dataIndex: 'title',
        key: 'title',
        width: 300
    },
    {
        title: '文章创建时间',
        dataIndex: 'creationTimestamp',
        key: 'creationTimestamp',
        width: 100,
        render: (record: number) => {
            console.log(record);
            return moment(record).format('YYYY-MM-DD')
        }
    },
    {
        title: '上次修改时间',
        dataIndex: 'lastModifiedTimestamp',
        key: 'lastModifiedTimestamp',
        width: 100,
        render: (record: number) => {
            console.log(record);
            return moment(record).format('YYYY-MM-DD')
        }
    }]

    render() {
        return (
            <div>
                <Spin spinning={this.state.isLoading}>
                    <Search placeholder="搜索" onSearch={values => this.onSearch(values)} allowClear={true} enterButton />
                    <Table columns={this.columns}
                        dataSource={this.state.ArticleSource}
                        pagination={{
                            onChange: (page, pageSize) => {
                                console.log(page, pageSize);
                                if (!!pageSize) {
                                    this.setState({
                                        offset: (page - 1) * (pageSize),
                                        limit: (pageSize)
                                    }, () => {
                                        this.getArticle()
                                    })
                                } else {
                                    console.error('pageSize === undefined')
                                }
                            },
                            defaultPageSize: this.state.limit,
                            total: this.state.amount,
                            showSizeChanger: false
                        }} />
                </Spin>
            </div>
        )
    }
}

//connect加入props
const mapStateToProps = (state: RootState) => {
    return {
        userID: state.loginReducers.userID,
        userType: state.loginReducers.userType
    }
}

const connector = connect(mapStateToProps)

export default connector(ArticleInfoList)